# == Schema Information
#
# Table name: carousels
#
#  id           :integer          not null, primary key
#  order_num    :integer
#  picture_src  :string(255)
#  picture_link :string(255)
#  created_at   :datetime         not null
#  updated_at   :datetime         not null
#

class Carousel < ApplicationRecord
  mount_uploader :picture_src, CarouselPictureUploader
  STATUS = {unpublished: 0, published: 1}

  extend Enumerize
  enumerize :status, :in => STATUS, predicates: {prefix: true}, scope: true

  after_save :reorder?
  after_destroy :reorder

  def http_picture_link
    return picture_link if picture_link.blank? || picture_link =~ /http/
    "http://#{picture_link}"
  end

  private

  def reorder?
    reorder if self.saved_change_to_order_num? || self.order_num.blank?
  end

  def reorder
    Carousel.where(order_num: self.order_num).where("id != #{self.id}").first.try(:update_column, :order_num, self.order_num_before_last_save)
    Carousel.all.order('order_num asc').each_with_index do |c, index|
      c.update_column(:order_num, index + 1)
    end
  end
end
